package io.finer.erp.jeecg.purchase.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.finer.erp.jeecg.purchase.entity.PurchaseOrderLine;
import io.finer.erp.jeecg.purchase.mapper.PurchaseOrderLineMapper;
import io.finer.erp.jeecg.purchase.service.PurchaseOrderLineService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.finer.erp.jeecg.purchase.vo.PurchaseOrderLinePage;
import io.finer.erp.jeecg.stock.entity.StockMove;
import io.finer.erp.jeecg.stock.service.StockMoveService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;

/**
 * <p>
 * 采购订单行 服务实现类
 * </p>
 *
 * @author yaoyifan
 * @since 2021-06-15
 */
@Service
public class PurchaseOrderLineServiceImpl extends ServiceImpl<PurchaseOrderLineMapper, PurchaseOrderLine> implements PurchaseOrderLineService {

    @Autowired
    StockMoveService stockMoveService;

    @Override
    public List<PurchaseOrderLinePage> selectPurchaseOrderLinePageByMid(String mid) {
        return this.baseMapper.selectPurchaseOrderLinePageByMid(mid);
    }

    @Override
    public void updateInQtyState(String id) {
        QueryWrapper<StockMove> stockMoveQueryWrapper = new QueryWrapper<>();
        stockMoveQueryWrapper.eq("ref_id", id).eq("state", "完成");
        List<StockMove> stockMoveList = stockMoveService.list(stockMoveQueryWrapper);
        PurchaseOrderLine purchaseOrderLine = this.baseMapper.selectById(id);
        BigDecimal qty = purchaseOrderLine.getQty();
        BigDecimal inQty = BigDecimal.valueOf(0);
        BigDecimal inAmount = BigDecimal.valueOf(0);
        for(StockMove stockMove: stockMoveList){
            inQty = inQty.add(stockMove.getQty());
            inAmount = inAmount.add(stockMove.getAmount());
        }
        if(qty.compareTo(inQty) == 0){
            purchaseOrderLine.setLineState("已入库");
        }else if(qty.compareTo(inQty) > 0){
            purchaseOrderLine.setLineState("部分入库");
        }
        purchaseOrderLine.setReceiptQty(inQty);
        purchaseOrderLine.setReceiptAmount(inAmount);
        this.baseMapper.updateById(purchaseOrderLine);
    }
}
